package com.companyname.demo.cod.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MultiThreadDateUtil {
    /**
     * 存放不同的日期模板格式的sdf的Map
     */
    private static ThreadLocal<Map<String, SimpleDateFormat>> sdfMap =
            new ThreadLocal<Map<String, SimpleDateFormat>>() {
                protected Map<String, SimpleDateFormat> initialValue() {
                    return new HashMap<String, SimpleDateFormat>();
                }
            };

    /**
     * 返回一个SimpleDateFormat,每个线程只会new一次pattern对应的sdf
     */
    private static SimpleDateFormat getSdf(String pattern) {
        Map<String, SimpleDateFormat> t = sdfMap.get();
        SimpleDateFormat sdf = t.get(pattern);
        if (sdf == null) {
            sdf = new SimpleDateFormat(pattern);
            t.put(pattern, sdf);
        }
        return sdf;
    }


    public static String format(Date date, String pattern) {
        return getSdf(pattern).format(date);
    }

    public static Date parse(String dateStr, String pattern) throws Exception {
        return getSdf(pattern).parse(dateStr);
    }

}

